import React, { useEffect, useRef, useState } from 'react'
import NavBar from '@/components/NavBar'
import styles from './index.module.scss'
import { List, DatePicker, Drawer } from 'antd-mobile'
import { useDispatch, useSelector } from 'react-redux'
import { getProfile, updatePhoto, updateProfile } from '@/store/actions/profile'
import classnames from 'classnames'
import EditInput from './component/EditInput'
import EditList from './component/EditList'
import { Toast, Modal } from 'antd-mobile'
import dayjs from 'dayjs'
import { useHistory } from 'react-router-dom'
import { logout } from '@/store/actions/login'
const { Item } = List
const alert = Modal.alert

export default function ProfileEdit() {
	const [open, setOpen] = useState({
		visible: false,
		type: '',
	})

	const [listOpen, setListOpen] = useState({
		visible: false,
		type: '',
	})

	const history = useHistory()

	const fileRef = useRef(null)

	const onClose = () => {
		setOpen({
			visible: false,
			type: '',
		})

		setListOpen({
			visible: false,
			type: '',
		})
	}

	const config = {
		photo: [
			{
				title: '拍照',
				onClick: () => {
					console.log('拍照')
				},
			},
			{
				title: '本地选择',
				onClick: () => {
					fileRef.current.click()
				},
			},
		],
		gender: [
			{
				title: '男',
				onClick: () => {
					onCommit('gender', 0)
				},
			},
			{
				title: '女',
				onClick: () => {
					onCommit('gender', 1)
				},
			},
		],
	}

	const onFileChange = async (e) => {
		const avatar = e.target.files[0]
		// ajax上传图片, 必须使用formData上传

		const formData = new FormData()
		formData.append('photo', avatar)

		await dispatch(updatePhoto(formData))
		Toast.success('修改头像成功')
		onClose()
	}

	const onBirthdayChange = (e) => {
		// e: date数据
		onCommit('birthday', dayjs(e).format('YYYY-MM-DD'))
	}

	const onCommit = async (type, value) => {
		await dispatch(
			updateProfile({
				[type]: value,
			})
		)

		Toast.success('修改成功', 1, null, false)
		onClose()
	}

	const logoutFn = () => {
		// 1. 显示弹窗
		alert('温馨提示', '你确定要退出吗?', [
			{ text: '取消' },
			{
				text: 'ok',
				// 2. 删除本地token和redux中的token
				onPress() {
					dispatch(logout())
					// 3. 跳转到登录页
					history.push('/login')

					Toast.success('退出登录成功')
				},
			},
		])
	}

	const dispatch = useDispatch()
	useEffect(() => {
		dispatch(getProfile())
	}, [dispatch])

	const profile = useSelector((state) => state.profile.profile)

	const { birthday, gender, name, photo, intro } = profile
	return (
		<div className={styles.root}>
			<div className="content">
				<NavBar>个人信息</NavBar>
				<div className="wrapper">
					<List className="profile-list">
						<Item
							arrow="horizontal"
							onClick={() => {
								setListOpen({ type: 'photo', visible: true })
							}}
							extra={
								<span className="avatar-wrapper">
									<img src={photo} />
								</span>
							}
						>
							头像
						</Item>
						<Item
							arrow="horizontal"
							onClick={() => {
								setOpen({ visible: true, type: 'name' })
							}}
							extra={name}
						>
							昵称
						</Item>
						<Item
							arrow="horizontal"
							onClick={() => {
								setOpen({ visible: true, type: 'intro' })
							}}
							extra={
								<span
									className={classnames(
										'intro',
										intro ? 'normal' : ''
									)}
								>
									{intro || '未填写'}
								</span>
							}
						>
							简介
						</Item>
					</List>

					<List className="profile-list">
						<Item
							extra={gender === 1 ? '女' : '男'}
							arrow="horizontal"
							onClick={() => {
								setListOpen({ type: 'gender', visible: true })
							}}
						>
							性别
						</Item>

						<DatePicker
							mode="date"
							title="选择生日"
							minDate={new Date('1900-01-01')}
							maxDate={new Date()}
							value={new Date(birthday)}
							onChange={onBirthdayChange}
						>
							<Item arrow="horizontal">生日</Item>
						</DatePicker>
					</List>

					<input
						type="file"
						hidden
						ref={fileRef}
						onChange={onFileChange}
					/>
				</div>

				<div className="logout">
					<button className="btn" onClick={logoutFn}>
						退出登录
					</button>
				</div>
			</div>

			<Drawer
				// 由于在组件中使用了useState的初始值, 而初始值只会执行一次, 因此需要在open.visible为true才能渲染组件
				// sidebar={ <EditInput onClose={onClose} type={open.type}/>}
				sidebar={
					open.visible && (
						<EditInput onClose={onClose} type={open.type} />
					)
				}
				open={open.visible}
				className="drawer"
				position="right"
				style={{ minHeight: document.documentElement.clientHeight }}
			>
				1
			</Drawer>

			{/* 列表的抽屉组件 */}
			<Drawer
				sidebar={
					listOpen.visible && (
						<EditList
							config={config}
							onClose={onClose}
							type={listOpen.type}
						/>
					)
				}
				className="drawer"
				position="bottom"
				open={listOpen.visible}
				style={{ minHeight: document.documentElement.clientHeight }}
				onOpenChange={onClose}
			>
				1
			</Drawer>
		</div>
	)
}
